package cn.kgc.springmvc02.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: mosin
 * @version: v1.0  2022/12/14
 * session和cookie的相关操作
 *
 * @SessionAttribute("key")  可以将session域中指定key对应的值取出
 * @CookieValue("ck")        可以将cookie中指定key对应的值取出
 */
@Controller
@RequestMapping("cs")
public class CSController {

    @RequestMapping("getCode")
    @ResponseBody
    public Map  getCode(HttpSession session){
        HashMap<String, Object> map = new HashMap<>();
        session.setAttribute("code", "qw123");
        map.put("code", 200);
        map.put("msg", "验证码获取成功");
        return  map;
    }

    @RequestMapping("login")
    @ResponseBody
    public Map  login(String captcha,HttpSession session){
        HashMap<String, Object> map = new HashMap<>();
        String code = (String) session.getAttribute("code");
        if(code.equals(captcha)){
            map.put("code", 200);
            map.put("msg", "验证码正确");
        }else {
            map.put("code", 500);
            map.put("msg", "验证码错误");

        }
        return  map;
    }

    @RequestMapping("login2")
    @ResponseBody
    public Map  login2(String captcha,@SessionAttribute("code") String code){
        HashMap<String, Object> map = new HashMap<>();
        if(code.equals(captcha)){
            map.put("code", 200);
            map.put("msg", "验证码正确");
        }else {
            map.put("code", 500);
            map.put("msg", "验证码错误");
        }
        return  map;
    }


    @RequestMapping("ck")
    @ResponseBody
    public void  method1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Cookie cookie = new Cookie("ck", "ckValue");
        response.addCookie(cookie);
        response.sendRedirect(request.getContextPath()+"/login.jsp");
    }


    @RequestMapping("ck2")
    @ResponseBody
    public Map  method2(@CookieValue("ck") String ck) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("ck", ck);
        map.put("msg", "验证码获取成功");
        return  map;
    }

}
